<template>
  <view class="order-list">
    <!-- 导航栏 -->
    <NavBar title="我的订单" />

    <!-- 订单状态选项卡 -->
    <nut-tabs v-model="activeTab" @click="onTabChange">
      <nut-tab-pane title="全部" pane-key="all" />
      <nut-tab-pane title="待付款" pane-key="unpaid" />
      <nut-tab-pane title="待发货" pane-key="unshipped" />
      <nut-tab-pane title="待收货" pane-key="unreceived" />
      <nut-tab-pane title="待评价" pane-key="unevaluated" />
    </nut-tabs>

    <!-- 订单列表 -->
    <view class="order-content">
      <!-- 空订单提示 -->
      <nut-empty v-if="orderList.length === 0" description="暂无相关订单" image="empty">
        <template #footer>
          <nut-button type="primary" size="small" @click="goShopping">去逛逛</nut-button>
        </template>
      </nut-empty>

      <!-- 订单列表 -->
      <view v-else class="order-items">
        <view class="order-item" v-for="(order, index) in orderList" :key="index" @click="goToOrderDetail(order.id)">
          <view class="order-header">
            <text class="order-no">订单号：{{ order.orderNo }}</text>
            <text class="order-status" :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</text>
          </view>

          <view class="order-goods">
            <view class="goods-item" v-for="(goods, goodsIndex) in order.goods" :key="goodsIndex">
              <image :src="goods.goods.cover" class="goods-image" />
              <view class="goods-info">
                <text class="goods-name">{{ goods.goods.title }}</text>
                <text class="goods-sku" v-if="goods.skuText">{{ goods.skuText }}</text>
                <view class="goods-price-qty">
                  <nut-price :price="goods.price" size="small" />
                  <text class="goods-qty">x{{ goods.quantity }}</text>
                </view>
              </view>
            </view>
          </view>

          <view class="order-footer">
            <view class="order-total">
              <text>共{{ getTotalQuantity(order) }}件商品 合计：</text>
              <nut-price :price="order.payAmount" size="normal" />
              <text class="small-text">(含运费)</text>
            </view>

            <view class="order-actions">
              <!-- 待付款 -->
              <template v-if="order.status === 1">
                <nut-button size="small" @click.stop="cancelOrder(order.id)">取消订单</nut-button>
                <nut-button size="small" type="primary" @click.stop="payOrder(order.id)">去支付</nut-button>
              </template>

              <!-- 待发货 -->
              <template v-else-if="order.status === 2">
                <nut-button size="small" @click.stop="viewLogistics(order.id)">查看物流</nut-button>
              </template>

              <!-- 待收货 -->
              <template v-else-if="order.status === 3">
                <nut-button size="small" @click.stop="viewLogistics(order.id)">查看物流</nut-button>
                <nut-button size="small" type="primary" @click.stop="confirmReceive(order.id)">确认收货</nut-button>
              </template>

              <!-- 待评价 -->
              <template v-else-if="order.status === 4">
                <nut-button size="small" type="primary" @click.stop="goToReview(order.id)">去评价</nut-button>
              </template>

              <!-- 已完成 -->
              <template v-else-if="order.status === 5">
                <nut-button size="small" @click.stop="deleteOrder(order.id)">删除订单</nut-button>
                <nut-button size="small" type="primary" @click.stop="rebuyOrder(order.id)">再次购买</nut-button>
              </template>

              <!-- 已取消 -->
              <template v-else-if="order.status === 0">
                <nut-button size="small" @click.stop="deleteOrder(order.id)">删除订单</nut-button>
              </template>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="orderList.length > 0" class="load-more">
      <view v-if="hasMore" class="loading" @click="loadMore">
        <nut-indicator size="16px" /> 加载中...
      </view>
      <view v-else class="no-more">没有更多了</view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import Taro from '@tarojs/taro'
import NavBar from '../../components/NavBar/index.vue'
import orderApi from '../../api/order'

// 获取路由参数
const router = Taro.getCurrentInstance().router
const initialStatus = router?.params?.status || 'all'

// 当前选中的状态标签
const activeTab = ref(initialStatus)

// 订单列表数据
const orderList = ref([])
const page = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)

// 状态映射
const statusMap = {
  all: '',
  unpaid: '1',
  unshipped: '2',
  unreceived: '3',
  unevaluated: '4',
  completed: '5',
  cancelled: '0'
}

// 获取订单列表
const fetchOrderList = (isLoadMore = false) => {
  const params = {
    page: page.value,
    pageSize: pageSize.value,
    status: statusMap[activeTab.value]
  }

  orderApi.getOrderList(params).then(res => {
    if (isLoadMore) {
      orderList.value = [...orderList.value, ...res.data.list]
    } else {
      orderList.value = res.data.list
    }
    hasMore.value = orderList.value.length < res.data.total
  }).catch(err => {
    Taro.showToast({
      title: err.message || '获取订单列表失败',
      icon: 'none'
    })
  })
}

// 加载更多
const loadMore = () => {
  if (!hasMore.value) return
  page.value++
  fetchOrderList(true)
}

// 标签切换
const onTabChange = () => {
  page.value = 1
  fetchOrderList()
}

// 监听标签变化
watch(activeTab, () => {
  page.value = 1
  fetchOrderList()
})

// 获取订单状态文本
const getStatusText = (status) => {
  const statusTexts = {
    0: '已取消',
    1: '待付款',
    2: '待发货',
    3: '待收货',
    4: '待评价',
    5: '已完成'
  }
  return statusTexts[status] || '未知状态'
}

// 获取状态样式类
const getStatusClass = (status) => {
  return `status-${status}`
}

// 计算订单商品总数量
const getTotalQuantity = (order) => {
  return order.goods.reduce((total, item) => total + item.quantity, 0)
}

// 跳转到订单详情
const goToOrderDetail = (id) => {
  Taro.navigateTo({
    url: `/pages/order/detail?id=${id}`
  })
}

// 取消订单
const cancelOrder = (id) => {
  Taro.showModal({
    title: '提示',
    content: '确定要取消该订单吗？',
    success: (res) => {
      if (res.confirm) {
        orderApi.cancelOrder(id).then(() => {
          Taro.showToast({
            title: '订单已取消',
            icon: 'success'
          })
          fetchOrderList()
        }).catch(err => {
          Taro.showToast({
            title: err.message || '取消订单失败',
            icon: 'none'
          })
        })
      }
    }
  })
}

// 支付订单
const payOrder = (id) => {
  Taro.navigateTo({
    url: `/pages/order/payment?id=${id}`
  })
}

// 查看物流
const viewLogistics = (id) => {
  Taro.navigateTo({
    url: `/pages/order/logistics?id=${id}`
  })
}

// 确认收货
const confirmReceive = (id) => {
  Taro.showModal({
    title: '提示',
    content: '确认已收到商品吗？',
    success: (res) => {
      if (res.confirm) {
        orderApi.confirmOrder(id).then(() => {
          Taro.showToast({
            title: '已确认收货',
            icon: 'success'
          })
          fetchOrderList()
        }).catch(err => {
          Taro.showToast({
            title: err.message || '确认收货失败',
            icon: 'none'
          })
        })
      }
    }
  })
}

// 去评价
const goToReview = (id) => {
  Taro.navigateTo({
    url: `/pages/order/review?id=${id}`
  })
}

// 删除订单
const deleteOrder = (id) => {
  Taro.showModal({
    title: '提示',
    content: '确定要删除该订单吗？',
    success: (res) => {
      if (res.confirm) {
        orderApi.deleteOrder(id).then(() => {
          Taro.showToast({
            title: '订单已删除',
            icon: 'success'
          })
          fetchOrderList()
        }).catch(err => {
          Taro.showToast({
            title: err.message || '删除订单失败',
            icon: 'none'
          })
        })
      }
    }
  })
}

// 再次购买
const rebuyOrder = (id) => {
  orderApi.rebuyOrder(id).then(() => {
    Taro.switchTab({
      url: '/pages/cart/index'
    })
  }).catch(err => {
    Taro.showToast({
      title: err.message || '操作失败',
      icon: 'none'
    })
  })
}

// 去购物
const goShopping = () => {
  Taro.switchTab({
    url: '/pages/index/index'
  })
}

// 页面加载
onMounted(() => {
  fetchOrderList()
})
</script>

<style lang="scss">
.load-more {
  padding: 16px 0;
  text-align: center;
  color: #999;
  font-size: 14px;
  
  .loading {
    display: flex;
    align-items: center;
    justify-content: center;
    
    .nut-icon {
      margin-right: 5px;
    }
  }
  
  .no-more {
    color: #999;
  }
}

.order-list {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.order-content {
  padding: 10px;
}

.order-items {
  .order-item {
    margin-bottom: 10px;
    border-radius: 8px;
    background-color: #fff;
    overflow: hidden;
    
    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px;
      border-bottom: 1px solid #f5f5f5;
      
      .order-no {
        font-size: 12px;
        color: #666;
      }
      
      .order-status {
        font-size: 14px;
        font-weight: bold;
        
        &.status-0 {
          color: #999; // 已取消
        }
        
        &.status-1 {
          color: #ff6b00; // 待付款
        }
        
        &.status-2 {
          color: #2196f3; // 待发货
        }
        
        &.status-3 {
          color: #ff9800; // 待收货
        }
        
        &.status-4 {
          color: #8bc34a; // 待评价
        }
        
        &.status-5 {
          color: #999; // 已完成
        }
      }
    }
    
    .order-goods {
      padding: 12px;
      
      .goods-item {
        display: flex;
        margin-bottom: 10px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .goods-image {
          width: 80px;
          height: 80px;
          border-radius: 4px;
          flex-shrink: 0;
        }
        
        .goods-info {
          flex: 1;
          margin-left: 10px;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          
          .goods-name {
            font-size: 14px;
            line-height: 1.4;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
          
          .goods-sku {
            font-size: 12px;
            color: #999;
            margin: 4px 0;
          }
          
          .goods-price-qty {
            display: flex;
            justify-content: space-between;
            align-items: center;
            
            .goods-qty {
              font-size: 12px;
              color: #999;
            }
          }
        }
      }
    }
    
    .order-footer {
      padding: 12px;
      border-top: 1px solid #f5f5f5;
      
      .order-total {
        text-align: right;
        margin-bottom: 10px;
        font-size: 14px;
        
        .small-text {
          font-size: 12px;
          color: #999;
          margin-left: 5px;
        }
      }
      
      .order-actions {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
      }
    }
  }
}
</style>